import React, { Component } from 'react'
import { Link } from "react-router-dom";
import InputWidget from '@/components/basicWidget/InputWidget/index.js'
import formValidate from '@/service/validate/formValidate';
import Button from '@/components/basicWidget/Button/index.js'
import { UserOutlined, LockOutlined, SafetyOutlined } from '@ant-design/icons'
import { post } from '@/utils/requestUtil.js'
import { withRouterContext } from '@/context/router/routerContext.js'
import CheckBoxWidget from '@/components/basicWidget/CheckBoxWidget';
import { message } from 'antd'
import secrecy from '@/service/secrecy/secrecyService';
import './index.css'

class Login extends Component {

  constructor(props) {
    super(props)
    this.state = {
      imageSrc: '/auth/getImage'
    }
  }

  //刷新验证码
  flushImage = async () => {
    const newImageSrc = '/auth/getImage?' + new Date().getTime()
    await new Promise((resolve) => {
      this.setState({
        imageSrc: newImageSrc
      }, resolve)
    })
  }

  //登陆操作
  doLogin = async () => {
    const { usernameInput, passwordInput, captchaInput, remeberMeInput } = this
    let refArray = [usernameInput, passwordInput, captchaInput]
    const validateResult = await formValidate.validateForm(refArray)
    if (validateResult === false) return false
    const response = await post('/auth/doLogin', {
      body: JSON.stringify({
        username: usernameInput.state.value,
        password: secrecy.AES_Encrypt(passwordInput.state.value),
        captcha: captchaInput.state.value,
        rememberMe: remeberMeInput.state.value.length > 0 ? true : false
      })
    })
    if (response && response.data && response.data.loginResult === true) {
      localStorage.setItem('token', response.data.token)
      const history = this.props.history
      if (history && history.length > 1) {
        this.props.navigate(history[history.length - 2].pathname)
      } else {
        this.props.navigate('/')
      }
    } else if (response && response.data && response.data.loginResult === false) {
      message.warning(response.message)
      this.flushImage()
      return false
    }
  }

  render() {
    return (
      <div
        className='login-main'
      >
        <div className='login-form-outDiv'>
          <form className='login-form'>
            <h1 style={{ color: 'var(--ordinary-font-color)', textAlign: 'center' }}>登录</h1>
            <InputWidget
              placeholder='请输入用户名'
              style={{ width: '300px', marginBottom: '15px' }}
              prefixName={{ content: <UserOutlined /> }}
              value={this.props.searchParams[0].get('username')}
              rules={
                [
                  {
                    validate: formValidate.getValidater('isMust'),
                    failMessage: '用户名不能为空'
                  }
                ]
              }
              ref={ref => {
                this.usernameInput = ref
              }}
            ></InputWidget>
            <InputWidget
              passwordInput={true}
              style={{ width: '300px', marginBottom: '15px' }}
              placeholder='请输入密码'
              prefixName={{ content: <LockOutlined /> }}
              rules={
                [
                  {
                    validate: formValidate.getValidater('isMust'),
                    failMessage: '密码不能为空'
                  }
                ]
              }
              ref={ref => {
                this.passwordInput = ref
              }}
            ></InputWidget>
            <div style={{
              display: 'flex',
              flexDirection: 'row',
              width: '300px'
            }}>
              <InputWidget
                style={{ height: '2.5em' }}
                placeholder='请输入验证码'
                prefixName={{ content: <SafetyOutlined /> }}
                rules={
                  [
                    {
                      validate: formValidate.getValidater('isMust'),
                      failMessage: '验证码不能为空'
                    }
                  ]
                }
                ref={ref => {
                  this.captchaInput = ref
                }}
              ></InputWidget>
              <div style={{ paddingLeft: '10px' }} onClick={this.flushImage}>
                <img src={this.state.imageSrc} alt='验证码' style={{ cursor: 'pointer' }} />
              </div>
            </div>
            <CheckBoxWidget
              style={{ marginBottom: '15px' }}
              paramCode='rememberMe'
              paramItem={[
                {
                  id: 'remember',
                  code: 'remember',
                  content: '记住我'
                }
              ]}
              hiddenClearButton={true}
              ref={ref => {
                this.remeberMeInput = ref
              }}
            ></CheckBoxWidget>
            <Button
              style={{
                width: '300px',
                background: 'var(--button-bg-color)',
                marginBottom: '15px',
                color: 'var(--button-font-color)'
              }}
              type='submit'
              onClick={this.doLogin}
            >
              登  录
            </Button>
            <div className='login-form-footer'>
              <Link to='/enroll'>注册帐号</Link>
              <Link to='/forget' style={{ float: 'right' }}>忘记密码</Link>
            </div>
          </form>
        </div >

      </div >
    )
  }
}

export default withRouterContext(Login)
